#!/bin/bash
#!/usr/bin/env bash
set -e

export PROJECT_PATH="${1}"
export BUILD_TYPE="${2}"
export IS_SIMULATOR="${3}"

export CANGJIE_IOS_PATH="$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-ios"

if [ "$IS_SIMULATOR" == "True" ]; then
    cangjieTarget="aarch64-apple-ios-simulator"
    export IOS_SIM_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/ios-sim"
    export IOS_SIM_ENGINE_PATH="$CJMP_SDK_HOME/ui-engine/ios-sim"
else
    cangjieTarget="aarch64-apple-ios"
    export IOS_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/ios"
    export IOS_ENGINE_PATH="$CJMP_SDK_HOME/ui-engine/ios"
fi

if [[ "$BUILD_TYPE" == "debug" ]]; then
    cangjieExtraArgs="-g"
else
    cangjieExtraArgs=""
fi

cd "$PROJECT_PATH/lib"
source "$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-ios/envsetup.sh"
cjpm build --no-feature-deduce --target="${cangjieTarget}" ${cangjieExtraArgs}

outputDir="$PROJECT_PATH/ios/frameworks"
if [ -d "${outputDir}" ]; then
    echo "Removing existing directory: ${outputDir}"
    rm -rf "${outputDir}"
fi
mkdir -p "${outputDir}"
soFilePath="$PROJECT_PATH/lib/target/${cangjieTarget}/$BUILD_TYPE/ohos_app_cangjie_entry/libohos_app_cangjie_entry.so"

if [[ ! -f "${soFilePath}" ]]; then
    echo "Error: Cannot find output library at ${soFilePath}" >&2
    exit 1
fi

cp "${soFilePath}" "${outputDir}/libohos_app_cangjie_entry.dylib"


if [ "$IS_SIMULATOR" == "True" ]; then
    cp -R "$IOS_SIM_ENGINE_PATH/libkeels_ios.framework" "${outputDir}"
    bash load_dependency.sh $soFilePath $IOS_SIM_CJ_FRONTEND $CANGJIE_IOS_PATH $outputDir $IS_SIMULATOR
else
    cp -R "$IOS_ENGINE_PATH/libkeels_ios.framework" "${outputDir}"
    bash load_dependency.sh $soFilePath $IOS_CJ_FRONTEND $CANGJIE_IOS_PATH $outputDir $IS_SIMULATOR
fi